#!/usr/bin/env python
#
# Copyright 2008 Richard J. Bell. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

""" WikiUser classes for great-loop site. """
# Google App Engine Imports
from google.appengine.api import users

# Application imports
from app.baserequesthandler import BaseRequestHandler
from model import WikiUser

#====== todo
class List(BaseRequestHandler):
  """ List extends the base request handler, and handles all
      requests to the url http://great-loop.appspot.com/userlist
  """
  def get(self):
    self.generate('userlist.html', 
                  template_values={'BrowserTitle': 'User List'}) 

#====== todo
class Info(BaseRequestHandler):
  """ List extends the base request handler, and handles all
      requests to the url http://great-loop.appspot.com/userinfo
  """
  def get(self, user):
    """ When requesting the URL, we find out that wiki user's WikiUser 
        information.
        We also retrieve articles written by the user.
    """
    # Webob over quotes the request URI, so we have to unquote twice
    unescaped_user = urllib.unquote(urllib.unquote(user))
    # Query for the user information
    user_object = users.User(unescaped_user)
    user = WikiUser.gql('WHERE user = :1', user_object).get()
    # Retrieve the unique set of articles the user has revised
    # Please note that this doesn't gaurentee that user's revision is
    # live on the wiki page
    article_list = []
    for article in user.wikirevision_set:
      article_list.append(article.wiki_page.title)
    articles = set(article_list)
    # If the user has specified a feed, fetch it
    feed_content = ''
    feed_titles = []
    if user.user_feed:
      feed = urlfetch.fetch(user.user_feed)
      # If the fetch is a success, get the blog article titles
      if feed.status_code == 200:
        feed_content = feed.content
        xml_content = xml.dom.minidom.parseString(feed_content)
        for title in xml_content.getElementsByTagName('title'):
          feed_titles.append(title.childNodes[0].nodeValue)
    # Generate the user profile
    self.generate('userinfo.html', 
                  template_values = {'queried_user': user,
                                     'articles': articles,
                                     'titles': feed_titles})

class Edit(BaseRequestHandler):
  """ Edit extends the base request handler, and handles all
      requests to the url http://great-loop.appspot.com/useredit
  """
  def get(self, user):
    # Get the user information
    unescaped_user = urllib.unquote(user)
    user_object = users.WikiUser(unescaped_user)
    # Only that user can edit his or her profile
    if users.get_current_user() != user_object:
      self.redirect('/view/StartPage')
    user = WikiUser.gql('WHERE user = :1', user_object).get()
    if not user:
      user = WikiUser(user=user_object)
      user.put()
    article_list = []
    for article in user.wikirevision_set:
      article_list.append(article.wiki_page.title)
    articles = set(article_list)
    self.generate('useredit.html', template_values={'queried_user': user,
                                                     'articles': articles})

  def post(self, user):
    # Get the user information
    unescaped_user = urllib.unquote(user)
    user_object = users.WikiUser(unescaped_user)
    # Only that user can edit his or her profile
    if users.get_current_user() != user_object:
      self.redirect('/view/StartPage')
    user = WikiUser.gql('WHERE user = :1', user_object).get()
    user_photo = self.request.get('user_picture')
    if user_photo:
      raw_photo = images.Image(user_photo)
      raw_photo.resize(width=256, height=256)
      raw_photo.im_feeling_lucky()
      user.user_picture = \
        raw_photo.execute_transforms(output_encoding=images.PNG)
    feed_url = self.request.get('feed_url')
    if feed_url:
      user.user_feed = feed_url
    user.put()
    self.redirect('/userinfo/%s' % user)

#====== todo
class GetPhoto(BaseRequestHandler):
  """ GetPhoto extends the base request handler, and handles all
      requests to the url http://great-loop.appspot.com/user todo
  """
  def get(self, user):
    unescaped_user = urllib.unquote(user)
    user_object = users.WikiUser(unescaped_user)
    # Only that user can edit his or her profile
    if users.get_current_user() != user_object:
      self.redirect('/view/StartPage')
    user = WikiUser.gql('WHERE user = :1', user_object).get()    
    if user.user_picture:
      self.response.headers['Content-Type'] = 'image/jpg'
      self.response.out.write(user.user_picture)
      
class UserSignIn( object ):
  """ Users must be signed in for various purposes.  This class enforces 
      this requirement.
  """
  @staticmethod
  def require_signin( requestObj=None, link_url='/about' ):
    """ Sign in the user if not already signed in.
    
        Parameters: str, Url for redirect if the user is not signed in
    
        Returns: 
          current_user - the currently loged in app server user
          wiki_user - the corresponding wiki_user object
    """
    # Make sure the user is signed in
    current_user = users.get_current_user()
    if not current_user:
      if not requestObj: return (None, None)
      requestObj.redirect(users.create_login_url( link_url ))
    # Make sure the user has a geo wiki profile
    wiki_user = WikiUser.gql('WHERE user = :1', current_user).get()
    # If not, create the profile
    if not wiki_user:
      wiki_user = WikiUser(user=current_user)
      wiki_user.put()
    return (current_user, wiki_user)


